package cn.sylinx.hbatis.ext.starter.common;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

class RelaxedPropertyResolver {

	private Properties properties;
	private String prefix;

	private Map<String, Object> kv = new HashMap<String, Object>();

	public RelaxedPropertyResolver(Properties properties, String prefix) {
		this.properties = properties;
		this.prefix = prefix;
		init();
	}

	private void init() {

		Set<Object> keySets = properties.keySet();
		if (keySets != null && !keySets.isEmpty()) {

			for (Object key : keySets) {
				if (key.toString().startsWith(prefix)) {
					kv.put(key.toString(), properties.get(key));
				}
			}
		}

	}

	public String getProperty(String key) {
		return getProperty(key, null);
	}

	public String getProperty(String key, String defaultValue) {
		String realKey = prefix + key;
		Object value = kv.get(realKey);
		if (value == null) {
			return defaultValue;
		}
		return value.toString();
	}

	public Map<String, Object> getSubProperties(String keyPrefix) {

		String fullPrefix = prefix + keyPrefix;
		Map<String, Object> kvtmp = new HashMap<String, Object>();
		Set<Object> keySets = properties.keySet();
		if (keySets != null && !keySets.isEmpty()) {

			for (Object key : keySets) {
				if (key.toString().startsWith(fullPrefix)) {
					String shotKey = key.toString().replaceFirst(fullPrefix, "");
					kvtmp.put(shotKey, properties.get(key));
				}
			}
		}
		return kvtmp;
	}
}
